package com.yuanfeng.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.goods.dto.GoodsTypeDTO;
import com.yuanfeng.goods.dto.MerchantGoodsTypeDTO;
import com.yuanfeng.goods.entity.*;
import com.yuanfeng.goods.mapper.*;
import com.yuanfeng.goods.service.GoodsTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class GoodsTypeServiceImpl extends ServiceImpl<GoodsTypeMapper, GoodsTypeEntity>
        implements GoodsTypeService {

    @Autowired
    private GoodsTypeBrandMapper goodsTypeBrandMapper;
    @Autowired
    private GoodsTypeSpecMapper goodsTypeSpecMapper;
    @Autowired
    private GoodsPropertyMapper goodsPropertyMapper;
    @Autowired
    private GoodsCommonMapper goodsCommonMapper;


    @Override
    public ResponseResult queryGoodsTypeById(MerchantGoodsTypeDTO merchantGoodsTypeReq) {
        if (null != merchantGoodsTypeReq && null != merchantGoodsTypeReq.getToken()) {
            //校验token
            String token = merchantGoodsTypeReq.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
            if (null != userInfo) {
                // 查询商品类型
                GoodsTypeEntity goodsType = this.baseMapper.selectById(merchantGoodsTypeReq.getTypeId());

                // 查询选中品牌
                List<GoodsTypeBrandEntity> typeBrands = goodsTypeBrandMapper.selectList(new LambdaQueryWrapper<GoodsTypeBrandEntity>()
                        .eq(GoodsTypeBrandEntity::getTypeId, merchantGoodsTypeReq.getTypeId()));

                // 查询选中的规格
                List<GoodsTypeSpecEntity> goodsTypeSpecs = goodsTypeSpecMapper.selectList(new LambdaQueryWrapper<GoodsTypeSpecEntity>()
                        .eq(GoodsTypeSpecEntity::getTypeId, merchantGoodsTypeReq.getTypeId()));

                // 查询所有的品牌
                List<GoodsTypeBrandEntity> allBrandList = goodsTypeBrandMapper.selectList(new LambdaQueryWrapper<GoodsTypeBrandEntity>());
                for (GoodsTypeBrandEntity allBrand : allBrandList) {
                    for (GoodsTypeBrandEntity typeBrand : typeBrands) {
                        if (allBrand.getBrandId().equals(typeBrand.getBrandId())) {
                            allBrand.setTypeBrandId(typeBrand.getTypeBrandId());
                        }
                    }
                }


                // 查询所有的规格
                List<GoodsTypeSpecEntity> allSpecList = goodsTypeSpecMapper.selectList(new LambdaQueryWrapper<GoodsTypeSpecEntity>());
                for (GoodsTypeSpecEntity allSpec : allSpecList) {
                    for (GoodsTypeSpecEntity goodsTypeSpec : goodsTypeSpecs) {
                        if (allSpec.getSpecId().equals(goodsTypeSpec.getSpecId())) {
                            allSpec.setTypeSpecId(goodsTypeSpec.getTypeSpecId());
                        }
                    }

                }

                // 查询所有的属性
                List<GoodsPropertyEntity> goodsPropertys = goodsPropertyMapper.selectList(new LambdaQueryWrapper<GoodsPropertyEntity>()
                        .eq(GoodsPropertyEntity::getTypeId, merchantGoodsTypeReq.getTypeId()));

                Map<String, Object> map = new HashMap<>();
                map.put("goodsType", goodsType);
                map.put("typeBrandList", allBrandList);
                map.put("goodsPropertys", goodsPropertys);
                map.put("typeSpecList", allSpecList);
                return ResponseResult.success(map);
            }
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
    }

    @Override
    public ResponseResult addTypeQuery() {
        Map<String, Object> map = new HashMap<>();
        // 查询所有规格
        List<GoodsTypeSpecEntity> allSpecList = goodsTypeSpecMapper.selectList(new LambdaQueryWrapper<GoodsTypeSpecEntity>());
        // 查询所有品牌
        List<GoodsTypeBrandEntity> allBrandList = goodsTypeBrandMapper.selectList(new LambdaQueryWrapper<GoodsTypeBrandEntity>());
        map.put("goodsBrandList", allBrandList);
        map.put("goodsSpecList", allSpecList);

        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult addGoodsType(GoodsTypeDTO goodsTypeAddparam) {
        if (null != goodsTypeAddparam && null != goodsTypeAddparam.getToken()) {
            //校验token
            String token = goodsTypeAddparam.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
            if (null != userInfo) {
                if (null == goodsTypeAddparam.getTypeId()) {
                    List<Integer> typeIds = this.baseMapper.selectList(new LambdaQueryWrapper<GoodsTypeEntity>()
                            .isNull(GoodsTypeEntity::getTypeName))
                            .stream().map(GoodsTypeEntity::getTypeId).collect(Collectors.toList());
                    //查询类型名称是否存在
                    Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<GoodsTypeEntity>()
                            .eq(GoodsTypeEntity::getTypeName, goodsTypeAddparam.getTypeName()));
                    if (null != count && count > 0) {
                        return ResponseResult.fail(BizCodeEnume.TYPE_ERROR.getCode(), BizCodeEnume.TYPE_ERROR.getMsg());
                    }

                    if (CollectionUtils.isEmpty(typeIds)) {
                        // 新增
                        this.baseMapper.insertType(goodsTypeAddparam);
                        Integer typeId = goodsTypeAddparam.getTypeId();
                        if (!CollectionUtils.isEmpty(goodsTypeAddparam.getTypeBrandList())) {
                            for (GoodsTypeBrandEntity brand : goodsTypeAddparam.getTypeBrandList()) {
                                brand.setTypeId(typeId);
                            }
                            goodsTypeBrandMapper.insertTypeBrandBatch(goodsTypeAddparam.getTypeBrandList());
                        }

                        if (!CollectionUtils.isEmpty(goodsTypeAddparam.getTypeSpecList())) {

                            for (GoodsTypeSpecEntity spec : goodsTypeAddparam.getTypeSpecList()) {
                                spec.setTypeId(typeId);
                            }
                            goodsTypeSpecMapper.insertTypeSpecBatch(goodsTypeAddparam.getTypeSpecList());

                        }
                    } else {
                        // 更新类型
                        goodsTypeAddparam.setTypeId(typeIds.get(0));
                        this.baseMapper.updateType(goodsTypeAddparam);
                        // 更新类型规格
                        updateTypeSpec(goodsTypeAddparam);
                        // 更新类型品牌
                        updateTypeBrand(goodsTypeAddparam);
                    }
                } else if (200 >= goodsTypeAddparam.getTypeDisplayorder()) {
                    // 更新类型
                    this.baseMapper.updateType(goodsTypeAddparam);
                    // 更新类型品牌
                    updateTypeBrand(goodsTypeAddparam);

                    // 更新类型规格
                    updateTypeSpec(goodsTypeAddparam);
                } else {
                    ResponseResult.fail(BizCodeEnume.DISPLAYORDER_ERROR.getCode(), BizCodeEnume.DISPLAYORDER_ERROR.getMsg());
                }
                return ResponseResult.success();
            }
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
    }

    @Override
    public ResponseResult deleteGoodsType(GoodsTypeDTO goodsTypeAddparam) {
        if (null != goodsTypeAddparam && null != goodsTypeAddparam.getToken()) {
            //校验token
            String token = goodsTypeAddparam.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
            if (null != userInfo) {
                Integer result = 0;
                //查询该类型是否有商品使用
                result = goodsCommonMapper.selectCount(new LambdaQueryWrapper<GoodsCommonEntity>()
                        .eq(GoodsCommonEntity::getTypeId,goodsTypeAddparam.getTypeId()));
                if (result == 0) {
                    this.baseMapper.deleteById(goodsTypeAddparam.getTypeId());
                    //删除品牌分类表管理关系
                    goodsTypeBrandMapper.delete(new LambdaQueryWrapper<GoodsTypeBrandEntity>()
                            .eq(GoodsTypeBrandEntity::getTypeId, goodsTypeAddparam.getTypeId()));
                    //删除商品类型与规格关系
                    goodsTypeSpecMapper.delete(new LambdaQueryWrapper<GoodsTypeSpecEntity>()
                            .eq(GoodsTypeSpecEntity::getTypeId, goodsTypeAddparam.getTypeId()));
                    return ResponseResult.success();
                } else {
                    return ResponseResult.fail(BizCodeEnume.TYPE_NOT_DELETE_ERROR.getCode(), BizCodeEnume.TYPE_NOT_DELETE_ERROR.getMsg());
                }
            }
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
    }

    @Override
    public ResponseResult queryGoodsTypeList(MerchantGoodsTypeDTO merchantGoodsTypeReq) {
        try {
            if (null != merchantGoodsTypeReq && null != merchantGoodsTypeReq.getToken()) {
                //校验token
                String token = merchantGoodsTypeReq.getToken();
                UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
                if (null != userInfo) {
                    //将对象转换为map
                    Map data = ParseMapUtils.beanToMap(merchantGoodsTypeReq);
                    if (merchantGoodsTypeReq.getPage() != null && merchantGoodsTypeReq.getLimit() != null) {
                        //分页查询商品类型数据
                        IPage<GoodsTypeEntity> page = this.page(new Query<GoodsTypeEntity>().getPage(data),
                                new LambdaQueryWrapper<GoodsTypeEntity>().orderByAsc(GoodsTypeEntity::getTypeDisplayorder));

                        return ResponseResult.success(PageUtils.getPage(page));
                    } else {
                        List<GoodsTypeEntity> list = this.baseMapper.selectList(new LambdaQueryWrapper<GoodsTypeEntity>().orderByAsc(GoodsTypeEntity::getTypeDisplayorder));
                        return ResponseResult.success(list);
                    }

                }
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
    }


    private void updateTypeSpec(GoodsTypeDTO param) {
        List<GoodsTypeSpecEntity> typeSpecList = param.getTypeSpecList();
        // 更新规格类型表
        if (CollectionUtils.isEmpty(typeSpecList)) {
            goodsTypeSpecMapper.insertTypeSpecBatch(typeSpecList);
        } else {
            List<Integer> removeSpecIds = Lists.newArrayList();
            List<GoodsTypeSpecEntity> addSpecs = Lists.newArrayList();
            List<GoodsTypeSpecEntity> updateSpecs = Lists.newArrayList();
            for (GoodsTypeSpecEntity typeSpec : typeSpecList) {
                typeSpec.setTypeId(param.getTypeId());
                if (null == typeSpec.getTypeSpecId()) {
                    addSpecs.add(typeSpec);
                } else {
                    updateSpecs.add(typeSpec);
                    removeSpecIds.add(typeSpec.getTypeSpecId());
                }
            }
            // 删除不需要的规格类型id
//            if (!CollectionUtils.isEmpty(removeSpecIds)) {
//                goodsTypeSpecMapper.deleteBatch(removeSpecIds);
//            }
            //删除直接已经存在的规格信息配置
            goodsTypeSpecMapper.delete(new LambdaQueryWrapper<GoodsTypeSpecEntity>()
                    .eq(GoodsTypeSpecEntity::getTypeId, param.getTypeId()));
            if (!CollectionUtils.isEmpty(addSpecs)) {
                goodsTypeSpecMapper.insertTypeSpecBatch(addSpecs);
            }
            if (!CollectionUtils.isEmpty(updateSpecs)) {
                goodsTypeSpecMapper.updateTypeSpecBatch(updateSpecs);
            }

        }
    }


    private void updateTypeBrand(GoodsTypeDTO param) {
        List<GoodsTypeBrandEntity> typeBrandList = param.getTypeBrandList();
        // 更新规格类型表
        if (CollectionUtils.isEmpty(typeBrandList)) {
            goodsTypeBrandMapper.insertTypeBrandBatch(typeBrandList);
        } else {
            List<Integer> removeSpecIds = Lists.newArrayList();
            List<GoodsTypeBrandEntity> addBrands = Lists.newArrayList();
            List<GoodsTypeBrandEntity> updateBrands = Lists.newArrayList();
            for (GoodsTypeBrandEntity typeBrand : typeBrandList) {
                typeBrand.setTypeId(param.getTypeId());
                if (null == typeBrand.getTypeBrandId()) {
                    addBrands.add(typeBrand);
                } else {
                    updateBrands.add(typeBrand);
                    removeSpecIds.add(typeBrand.getTypeBrandId());
                }
            }
            // 删除不需要的规格类型id
//            if (!CollectionUtils.isEmpty(removeSpecIds)) {
//                goodstypeBrandMapper.deleteBatch(removeSpecIds);
//            }
            //删除直接已经存在的品牌信息配置
            goodsTypeBrandMapper.delete(new LambdaQueryWrapper<GoodsTypeBrandEntity>()
                    .eq(GoodsTypeBrandEntity::getTypeId, param.getTypeId()));
            if (!CollectionUtils.isEmpty(addBrands)) {
                goodsTypeBrandMapper.insertTypeBrandBatch(addBrands);
            }
            if (!CollectionUtils.isEmpty(updateBrands)) {
                goodsTypeBrandMapper.updateTypeBrandBatch(updateBrands);
            }

        }
    }
}




